#include "include/state_config_manager.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include "dlog/dlog.h"
// DLOG_MODULE_DEFINE(NodeCamdar1)

// 获取单例实例
StateConfigManager& StateConfigManager::getInstance() {
    static StateConfigManager instance; // 全局唯一实例
    return instance;
}


void StateConfigManager::Init()
{
    readDefaultConfig(json_config_path_);
    readAppData();
    printConfig();

}



Config& StateConfigManager::getConfig()
{
    return config;
}

bool StateConfigManager::getLogic()
{
    return bLogic;
}


bool StateConfigManager::getSwitch()
{
    return bSwitch;
}
void StateConfigManager::setAppData(int status, int sensor, float heihgt)
{
    LOG_CRITICAL("receive  STATUS:{} {} {} ", status, sensor, heihgt);

    if(status == 0) setSensor0(status, sensor, heihgt);
    else if (status == 1) setSensor2(status, sensor, heihgt);
     
    // setSensor(sensor);
    // setStatus(status);
    // setHeight(heihgt);

}

void StateConfigManager::setSensor0(int status, int sensor, float lower_altitude)
{
    LOG_CRITICAL("update app date from app:");
    int value1 = 0;    
    float value2 = 0.25; 
    getAppData(value1, value2);
    // tmp test ai
    // if(lower_altitude = 0.1) lower_altitude = 1.0;
    updateAppData(sensor, lower_altitude);
    // SENSOR_FUNCTION = sensor;
    // LOWER_AIMS_ATTITUDE = lower_altitude;
    config.module_function.sensor = sensor;
    config.car_config.lower_attitude = lower_altitude;

    if(value1 == sensor)
    {
        bSwitch = false;
        LOG_CRITICAL("update app un-data from app : bSwitch: {}", bSwitch);

    }
    else
    {
        bSwitch = true;
        LOG_CRITICAL("update app data from app: bSwitch: {}", bSwitch);

    }
    LOG_CRITICAL("update  STATUS:{} {} {} ", status, sensor, lower_altitude);

}

void StateConfigManager::setSensor2(int status, int sensor, float lower_altitude)
{
    LOG_CRITICAL("update rlm status from logic:");
    int value1 = 0;    
    float value2 = 0.25; 
    getAppData(value1, value2); 
    if(sensor == value1)
    {
        bSwitch = false;
        LOG_CRITICAL("obtain rlm un-data from logic: bSwitch: {}", bSwitch);

    }
    else
    {
        bSwitch = true;
        LOG_CRITICAL("obtain app data from logic: bSwitch: {}", bSwitch);

    }

    if(sensor == 0)
    {
        bLogic = true;
        ;
    }
    else if(sensor == 2)
    {
        bLogic = true;
        value1 = 2;

    }
    else if(sensor == -1)
    {
        value1 = -1;
        bLogic = false;
    }
    config.module_function.sensor = value1;
    config.car_config.lower_attitude = value2;
    LOG_CRITICAL("obtain  STATUS:{} {} {} ", status, sensor, lower_altitude);
    if(config.module_function.sensor  != -1)
    {
        long long init_time = getLocalMachineTime();
        ai_pre_time = init_time;
        li_pre_time = init_time;

        LOG_CRITICAL("Init Sensor time: {} ", li_pre_time);

    }

}
long long StateConfigManager::getAiPreTime()
{
    return ai_pre_time;
}

long long StateConfigManager::getLiPreTime()
{
    return li_pre_time;
}

void StateConfigManager::updateAiPreTime()
{
    ai_pre_time = getLocalMachineTime();
}

void StateConfigManager::updateLiPreTime()
{
    li_pre_time = getLocalMachineTime();
}

long long StateConfigManager::getLocalMachineTime()
{
    struct timeval time1;
    gettimeofday(&time1, NULL);
    long long cur_time = time1.tv_sec * 1000 + time1.tv_usec / 1000;

    return cur_time;
}
void StateConfigManager::getAppData1(int &outSensor, int &outStatus, float &outHeight) const 
{
    outStatus = iStatus.load();
    outSensor = iSensor.load();   
    outHeight = fHeight.load();
}

void StateConfigManager::getAppData(int &num1, float &num2) 
{
    std::ifstream file(SAVE_APP_TXT);  // 固定文件名 a.txt
    if (!file.is_open()) {
        std::cerr << "unopen: a.txt" << std::endl;
        return;  // 如果文件无法打开，直接返回
    }

    std::string line1, line2;

    // 读取第一行和第二行
    std::getline(file, line1);
    std::getline(file, line2);

    file.close();  // 关闭文件

    // 将读取的字符串转换为数值
    num1 = std::stoi(line1);   // 第一行转为整数
    num2 = std::stod(line2);   // 第二行转为浮点数
}



void StateConfigManager::setStatus(int status)
{
    iStatus.store(status);
}

void StateConfigManager::setSensor(int sensor)
{
    config.module_function.sensor = sensor;
    iSensor.store(sensor);
}

void StateConfigManager::setHeight(float height)
{
    config.car_config.lower_attitude = height;
    fHeight.store(height);
}

bool StateConfigManager::updateAppData(int sensor, float lower_altitude)
{
    // std::ifstream infile(SAVE_APP_TXT); // 尝试打开文件
    // 打开文件进行写操作（覆盖模式）
    std::ofstream outfile(SAVE_APP_TXT, std::ios::trunc); // std::ios::trunc 模式会清空文件内容

    if (!outfile) {
        std::cerr << "not open: " << SAVE_APP_TXT << std::endl;
        return 1;
    }

    // 写入新的数据
    outfile << sensor << std::endl;    // 写入第一行数据
    outfile << lower_altitude << std::endl;  // 写入第二行数据

    outfile.close();

    return 0;
}




void StateConfigManager::readAppData()
{
    // SENSOR_FUNCTION
    // LOWER_AIMS_ATTITUDE
    std::ifstream infile(SAVE_APP_TXT); // 尝试打开文件

    if (!infile) { // 如果文件不存在
        std::cout << "ERROE not find" << std::endl;


        // 创建并写入数据
        std::ofstream outfile(SAVE_APP_TXT); // 创建文件
        if (outfile) {
            // outfile << SENSOR_FUNCTION  << std::endl;   // 写入第一行
            // outfile << LOWER_AIMS_ATTITUDE << std::endl; // 写入第二行
            outfile << config.module_function.sensor  << std::endl;   // 写入第一行
            outfile << config.car_config.lower_attitude << std::endl; // 写入第二行
            outfile.close();              // 关闭文件
            LOG_CRITICAL("write default data to txt:{} {}", config.module_function.sensor, config.car_config.lower_attitude );

        } else {
            std::cerr << "ERROR1!" << std::endl;
            return ;
        }
    } else { // 如果文件存在
        LOG_CRITICAL("read default app data:");
        // 从文件中读取数据
        std::string line1, line2;
        if (std::getline(infile, line1) && std::getline(infile, line2)) {

            int value1 = std::stoi(line1);     // 转换为 int
            float value2 = std::stof(line2);   // 转换为 float
            config.module_function.sensor = value1;
             config.car_config.lower_attitude = value2;
            LOG_CRITICAL("read default app data: {} {}",value1, value2);


        } else {
            std::cerr << "ERROR!" << std::endl;
        }
        infile.close(); // 关闭文件
    }

    return ;

}

// 解析函数：解析 save_flag
void StateConfigManager::parseSaveFlag(const rapidjson::Value& saveFlag, SaveFlag& save_flag) {
    if (saveFlag.HasMember("save") && saveFlag["save"].IsBool()) {
        save_flag.save = saveFlag["save"].GetBool();
    }
    if (saveFlag.HasMember("simpify") && saveFlag["simpify"].IsBool()) {
        save_flag.simpify = saveFlag["simpify"].GetBool();
    }
    if (saveFlag.HasMember("dense") && saveFlag["dense"].IsBool()) {
        save_flag.dense = saveFlag["dense"].GetBool();
    }
}

// 解析函数：解析 time_interval
void StateConfigManager::parseTimeInterval(const rapidjson::Value& timeInterval, TimeInterval& time_interval) {
    if (timeInterval.HasMember("time_diff") && timeInterval["time_diff"].IsInt()) {
        time_interval.time_diff = timeInterval["time_diff"].GetInt();
    }
    if (timeInterval.HasMember("lidar_interval") && timeInterval["lidar_interval"].IsInt()) {
        time_interval.lidar_interval = timeInterval["lidar_interval"].GetInt();
    }
    if (timeInterval.HasMember("ai_interval") && timeInterval["ai_interval"].IsInt()) {
        time_interval.ai_interval = timeInterval["ai_interval"].GetInt();
    }
    if (timeInterval.HasMember("ai_delay") && timeInterval["ai_delay"].IsInt()) {
        time_interval.ai_delay = timeInterval["ai_delay"].GetInt();
    }
}

// 解析函数：解析 car_config
void StateConfigManager::parseCarConfig(const rapidjson::Value& carConfig, CarConfig& car_config) {
    if (carConfig.HasMember("car_behind") && carConfig["car_behind"].IsDouble()) {
        car_config.car_behind = carConfig["car_behind"].GetDouble();
    }
    if (carConfig.HasMember("dwn_dis") && carConfig["dwn_dis"].IsDouble()) {
        car_config.dwn_dis = carConfig["dwn_dis"].GetDouble();
    }
    if (carConfig.HasMember("lidar_attitude") && carConfig["lidar_attitude"].IsDouble()) {
        car_config.lidar_attitude = carConfig["lidar_attitude"].GetDouble();
    }
    if (carConfig.HasMember("lower_attitude") && carConfig["lower_attitude"].IsDouble()) {
        car_config.lower_attitude = carConfig["lower_attitude"].GetDouble();
    }
    if (carConfig.HasMember("lidar_front") && carConfig["lidar_front"].IsDouble()) {
        car_config.lidar_front = carConfig["lidar_front"].GetDouble();
    }
    if (carConfig.HasMember("lidar_sides") && carConfig["lidar_sides"].IsDouble()) {
        car_config.lidar_sides = carConfig["lidar_sides"].GetDouble();
    }
}

// 解析函数：解析 debug_info
void StateConfigManager::parseDebugInfo(const rapidjson::Value& debugInfo, DebugInfo& debug_info) {
    if (debugInfo.HasMember("debug_ai") && debugInfo["debug_ai"].IsInt()) {
        debug_info.debug_ai = debugInfo["debug_ai"].GetInt();
    }
    if (debugInfo.HasMember("debug_lidar") && debugInfo["debug_lidar"].IsInt()) {
        debug_info.debug_lidar = debugInfo["debug_lidar"].GetInt();
    }
    if (debugInfo.HasMember("debug_camdar") && debugInfo["debug_camdar"].IsInt()) {
        debug_info.debug_camdar = debugInfo["debug_camdar"].GetInt();
    }
}

// 解析函数：解析 cam_inttri
void StateConfigManager::parseCamIntTri(const rapidjson::Value& camIntTri, CamIntTri& cam_inttri) {
    if (camIntTri.HasMember("fx") && camIntTri["fx"].IsDouble()) {
        cam_inttri.fx = camIntTri["fx"].GetDouble();
    }
    if (camIntTri.HasMember("fy") && camIntTri["fy"].IsDouble()) {
        cam_inttri.fy = camIntTri["fy"].GetDouble();
    }
    if (camIntTri.HasMember("cx") && camIntTri["cx"].IsDouble()) {
        cam_inttri.cx = camIntTri["cx"].GetDouble();
    }
    if (camIntTri.HasMember("cy") && camIntTri["cy"].IsDouble()) {
        cam_inttri.cy = camIntTri["cy"].GetDouble();
    }
    if (camIntTri.HasMember("x_cam") && camIntTri["x_cam"].IsDouble()) {
        cam_inttri.x_cam = camIntTri["x_cam"].GetDouble();
    }
    if (camIntTri.HasMember("y_cam") && camIntTri["y_cam"].IsDouble()) {
        cam_inttri.y_cam = camIntTri["y_cam"].GetDouble();
    }
    if (camIntTri.HasMember("z_cam") && camIntTri["z_cam"].IsDouble()) {
        cam_inttri.z_cam = camIntTri["z_cam"].GetDouble();
    }
    if (camIntTri.HasMember("rx") && camIntTri["rx"].IsDouble()) {
        cam_inttri.rx = camIntTri["rx"].GetDouble();
    }
    if (camIntTri.HasMember("ry") && camIntTri["ry"].IsDouble()) {
        cam_inttri.ry = camIntTri["ry"].GetDouble();
    }
    if (camIntTri.HasMember("rz") && camIntTri["rz"].IsDouble()) {
        cam_inttri.rz = camIntTri["rz"].GetDouble();
    }
    if (camIntTri.HasMember("upper_pixel") && camIntTri["upper_pixel"].IsInt()) {
        cam_inttri.upper_pixel = camIntTri["upper_pixel"].GetInt();
    }
    if (camIntTri.HasMember("lower_pixel") && camIntTri["lower_pixel"].IsInt()) {
        cam_inttri.lower_pixel = camIntTri["lower_pixel"].GetInt();
    }
}

// 主函数：读取 JSON 文件并解析
void StateConfigManager::readDefaultConfig(const std::string& json_config_path) {
    FILE* fp = fopen(json_config_path.c_str(), "r");
    if (!fp) {
        std::cerr << "Could not open file! Using default values." << std::endl;
        return;
    }

    char readBuffer[4096];
    rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));

    rapidjson::Document document;
    document.ParseStream(is);
    fclose(fp);

    if (!document.IsObject()) {
        std::cerr << "Invalid JSON format! Using default values." << std::endl;
        return;
    }

    // Config config;

    if (document.HasMember("name") && document["name"].IsString()) {
        config.name = document["name"].GetString();
    }
    if (document.HasMember("version") && document["version"].IsDouble()) {
        config.version = document["version"].GetDouble();
    }
    if (document.HasMember("save_flag") && document["save_flag"].IsObject()) {
        parseSaveFlag(document["save_flag"], config.save_flag);
    }
    if (document.HasMember("time_interval") && document["time_interval"].IsObject()) {
        parseTimeInterval(document["time_interval"], config.time_interval);
    }
    if (document.HasMember("car_config") && document["car_config"].IsObject()) {
        parseCarConfig(document["car_config"], config.car_config);
    }
    if (document.HasMember("debug_info") && document["debug_info"].IsObject()) {
        parseDebugInfo(document["debug_info"], config.debug_info);
    }
    if (document.HasMember("cam_inttri") && document["cam_inttri"].IsObject()) {
        parseCamIntTri(document["cam_inttri"], config.cam_inttri);
    }

    // 输出验证
    std::cout << "Name: " << config.name << std::endl;
    std::cout << "Version: " << config.version << std::endl;
}


void StateConfigManager::printConfig() const {
    std::cout << "Config Details:" << std::endl;
    std::cout << "Name: " << config.name << std::endl;
    std::cout << "Version: " << config.version << std::endl;

    // 打印 save_flag
    std::cout << "SaveFlag:" << std::endl;
    std::cout << "  save: " << (config.save_flag.save ? "true" : "false") << std::endl;
    std::cout << "  simpify: " << (config.save_flag.simpify ? "true" : "false") << std::endl;
    std::cout << "  dense: " << (config.save_flag.dense ? "true" : "false") << std::endl;

    // 打印 time_interval
    std::cout << "TimeInterval:" << std::endl;
    std::cout << "  time_diff: " << config.time_interval.time_diff << std::endl;
    std::cout << "  lidar_interval: " << config.time_interval.lidar_interval << std::endl;
    std::cout << "  ai_interval: " << config.time_interval.ai_interval << std::endl;
    std::cout << "  ai_delay: " << config.time_interval.ai_delay << std::endl;

    // 打印 car_config
    std::cout << "CarConfig:" << std::endl;
    std::cout << "  car_behind: " << config.car_config.car_behind << std::endl;
    std::cout << "  dwn_dis: " << config.car_config.dwn_dis << std::endl;
    std::cout << "  lidar_attitude: " << config.car_config.lidar_attitude << std::endl;
    std::cout << "  lower_attitude: " << config.car_config.lower_attitude << std::endl;
    std::cout << "  lidar_front: " << config.car_config.lidar_front << std::endl;
    std::cout << "  lidar_sides: " << config.car_config.lidar_sides << std::endl;

    // 打印 debug_info
    std::cout << "DebugInfo:" << std::endl;
    std::cout << "  debug_ai: " << config.debug_info.debug_ai << std::endl;
    std::cout << "  debug_lidar: " << config.debug_info.debug_lidar << std::endl;
    std::cout << "  debug_camdar: " << config.debug_info.debug_camdar << std::endl;

    // 打印 cam_inttri
    std::cout << "CamIntTri:" << std::endl;
    std::cout << "  fx: " << config.cam_inttri.fx << std::endl;
    std::cout << "  fy: " << config.cam_inttri.fy << std::endl;
    std::cout << "  cx: " << config.cam_inttri.cx << std::endl;
    std::cout << "  cy: " << config.cam_inttri.cy << std::endl;
    std::cout << "  x_cam: " << config.cam_inttri.x_cam << std::endl;
    std::cout << "  y_cam: " << config.cam_inttri.y_cam << std::endl;
    std::cout << "  z_cam: " << config.cam_inttri.z_cam << std::endl;
    std::cout << "  rx: " << config.cam_inttri.rx << std::endl;
    std::cout << "  ry: " << config.cam_inttri.ry << std::endl;
    std::cout << "  rz: " << config.cam_inttri.rz << std::endl;
    std::cout << "  upper_pixel: " << config.cam_inttri.upper_pixel << std::endl;
    std::cout << "  lower_pixel: " << config.cam_inttri.lower_pixel << std::endl;
}

bool StateConfigManager::sendStatus(int& res_sensor, int& res_stauts, int& res_ai_status, int& res_li_status, 
                                    long long& res_ai_pre_time, long long& res_li_pre_time)
{
    long long cur_local_time = getLocalMachineTime();
    int ai_status = 0;
    int li_status = 0;
    int status = 0;
    bool res = false;

    auto diff_ai = cur_local_time - ai_pre_time;
    auto diff_li = cur_local_time - li_pre_time;
    if(diff_ai > 10  * 1000)
    {
        ai_status = -1;
    }
    if(diff_li > 10  * 1000)
    {
        li_status = -1;
    }
    if(ai_status == -1 && li_status == -1)
    {
        status = -3;
    }
    else if(ai_status == -1 && li_status == 0)
    {
        status = -1;
    }
    else if (ai_status == 0 && li_status == -1)
    {
        status = -2;
    }
    int SENSOR_FUNCTION = config.module_function.sensor;
    if(status < 0 && bLogic == true)
    {
        if(SENSOR_FUNCTION == 0)
        {
            res_sensor = SENSOR_FUNCTION;
            res_stauts = status;
            res_ai_status = ai_status;
            res_li_status = li_status;
            res_ai_pre_time = ai_pre_time;
            res_li_pre_time = li_pre_time;
            res = true;
        }
        else if(SENSOR_FUNCTION == 1)
        {
            ;
        }
        else if(SENSOR_FUNCTION == 2)
        {
            if(status == -3) status = -2;

            res_sensor = SENSOR_FUNCTION;
            res_stauts = status;
            res_ai_status = ai_status;
            res_li_status = li_status;
            res_ai_pre_time = ai_pre_time;
            res_li_pre_time = li_pre_time;
            res = true;

        }
        else if(SENSOR_FUNCTION == -1)
        {
            ;
        }
    }


    return res;
}



    